package com.power.web.action.tiCase;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.power.Constants;
import com.power.model.dataDictionary.TddData;
import com.power.model.tiCase.TICase;
import com.power.model.user.TsSysuser;
import com.power.services.dataDictionary.DataDictionaryService;
import com.power.services.tiCase.TiCaseService;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.FileUtil;
import com.power.util.RequestUtil;
import com.power.util.XmlUtil;
import com.power.web.action.base.AbstractBaseAction;

public class TiCaseAction extends AbstractBaseAction {
    
    /**
     * 序列号
     */
    private static final long serialVersionUID = -5379265463153802690L;
    
    private static final String CONTENT_TYPE = "text/html; charset=GBK";
    
    @Autowired
    private TiCaseService tiCaseService;
    
    @Autowired
    private DataDictionaryService dataDictionaryService;
    
    private String jsonString;
    
    private TICase tiCase;
    
    private List deplist;
    
    private String flag;
    
    private File imgFile;
    
    private String imgFileFileName;
    
    private String if_has_File;
    
    public String showPage() {
        try {
            TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
            Integer caseId = RequestUtil.getParam(request, "caseId", -1);
            if (-1 == caseId && null != userInfo) {
                tiCase = new TICase();
                tiCase.setIdcard(userInfo.getIdcard());
                tiCase.setName(userInfo.getRealName());
                String bir = "";
                if (null != userInfo.getIdcard())
                    if (userInfo.getIdcard().length() == 15) {
                        bir =
                            "19" + userInfo.getIdcard().substring(6, 8) + "-" + userInfo.getIdcard().substring(8, 10)
                                + "-" + userInfo.getIdcard().substring(10, 12);
                        String year = "19" + userInfo.getIdcard().substring(6, 8);
                        tiCase.setAge((Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date())) - Integer.parseInt(year)));
                        if (new Integer(userInfo.getIdcard().charAt(14) / 2) * 2 != userInfo.getIdcard().charAt(14))
                            tiCase.setSex("1");
                        else
                            tiCase.setSex("2");
                    }
                    else {
                        bir =
                            userInfo.getIdcard().substring(6, 10) + "-" + userInfo.getIdcard().substring(10, 12) + "-"
                                + userInfo.getIdcard().substring(12, 14);
                        tiCase.setAge((Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date())) - Integer.parseInt(tiCase.getIdcard()
                            .substring(6, 10))));
                        if (new Integer(userInfo.getIdcard().charAt(16) / 2) * 2 != userInfo.getIdcard().charAt(16))
                            tiCase.setSex("1");
                        else
                            tiCase.setSex("2");
                    }
                tiCase.setBirthday(DateTimeUtil.switchStringToDate1(bir));
                
            }
            else
                tiCase = tiCaseService.read(caseId);
            deplist = dataDictionaryService.findAllDataByDDID(2);
            ActionContext.getContext().put("flag", flag);
        }
        catch (Exception e) {
        }
        return "showPage";
    }
    
    /**
     * 后台查看病历
     * 
     * @return
     */
    public String onViewPage() {
        Integer caseId = RequestUtil.getParam(request, "caseId", -1);
        tiCase = tiCaseService.read(caseId);
        deplist = dataDictionaryService.findAllDataByDDID(2);
        return "onViewPage";
    }
    
    /**
     * 查询病例
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String searchMember() {
        try {
            int start = this.start;
            int limit = this.limit;
            if (limit == 0)
                limit = 20;
            Integer dpartId = RequestUtil.getParam(request, "dpartId", -1);
            String startDate = RequestUtil.getParam(this.request, "startTime", "-1");
            String endDate = RequestUtil.getParam(this.request, "endTime", "-1");
            String idcard = RequestUtil.getParam(this.request, "idcard", "-1");
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("start", start + "");
            paraMap.put("limit", limit + "");
            paraMap.put("dpartId", dpartId.toString());
            paraMap.put("startDate", startDate);
            paraMap.put("endDate", endDate);
            paraMap.put("idcard", idcard);
            Map<String, Object> dataMap = tiCaseService.findTsCase(paraMap);
            StringBuffer jsonStr = new StringBuffer();
            String callback = this.callback;
            List<TICase> data = (List<TICase>)dataMap.get("data");
            int count = Integer.parseInt(dataMap.get("count").toString());
            jsonStr.append(callback).append("({\"total\":").append(count).append(",\"results\":");
            JsonConfig jsonconfig = new JsonConfig();
            jsonconfig.registerJsonValueProcessor("createTime", new DateJsonValueProcessor("yyyy-MM-dd"));
            jsonconfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
            JSONArray arry = JSONArray.fromObject(data, jsonconfig);
            jsonStr.append(arry.toString());
            jsonStr.append("})");
            this.jsonString = jsonStr.toString();
            
        }
        catch (Exception e) {
            log.error("病例查询失败！", e);
            this.jsonString = "[]";
        }
        this.response.setCharacterEncoding("UTF-8");
        try {
            this.response.getWriter().print(jsonString);
        }
        catch (IOException e) {
            log.error("病例查询io异常!", e);
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 
     * 删除病例
     * 
     * @return
     */
    public String delTiCase() {
        try {
            String json = "{failure:true,msg:'病历删除失败！'}";
            String deleteIds = request.getParameter("deleteID");
            tiCaseService.deleteCase(deleteIds);
            json = "{success:true, msg:'病历删除成功！'}";
            this.response.setCharacterEncoding("UTF-8");
            this.response.getWriter().print(json);
        }
        catch (Exception e) {
            log.error("病例删除失败！", e);
        }
        return null;
    }
    
    /**
     * 
     * 处理操作
     * 
     * @return
     */
    public String operRead() {
        String flag = null;
        
        try {
            String id = request.getParameter("id");
            flag = request.getParameter("flag");
            String json = "{failure:true,msg:'病历处理失败！'}";
            tiCaseService.updateCaseRead(id, flag);
            json = "{success:true, msg:'病历处理失败成功！'}";
            this.response.setCharacterEncoding("UTF-8");
            this.response.getWriter().print(json);
        }
        catch (Exception e) {
            log.error("病例处理失败！", e);
        }
        return null;
    }
    
    /**
     * 增加或者修改病例
     */
    public String saveOrUpdate() {
        try {
            TsSysuser loginUser = null;
            Object obj = this.session.get(Constants.USERINFO_KEY);
            if (obj != null) {
                loginUser = (TsSysuser)obj;
            }
            if (tiCase.getId() == null) {
                tiCase.setCreateTime(new Date());
            }
            else {
                TICase tempCase = tiCaseService.read(tiCase.getId());
                tiCase.setCreateTime(tempCase.getCreateTime());
            }
            tiCase.setAuthorId(loginUser.getId());
            tiCaseService.create(tiCase);
            request.setAttribute("ifsuccess", "保存成功!");
        }
        catch (Exception e) {
            log.error("病例增加失败！", e);
            request.setAttribute("ifsuccess", "保存失败!");
        }
        return "ifsuccess";
    }
    
    /**
     * 加载 病例信息
     */
    public String loadCase() {
        Integer caseId = RequestUtil.getParam(request, "caseId", -1);
        try {
            TICase tempCase = tiCaseService.read(caseId);
            this.request.setAttribute("tiCase", tempCase);
        }
        catch (Exception e) {
            log.error("病例加载失败！", e);
        }
        return "showPage";
    }
    
    /**
     * 加载科室
     */
    public String loadDepartMent() {
        String code = RequestUtil.getParam(request, "code", "dep");
        List<TddData> list = dataDictionaryService.findAllDataByCode(code);
        this.response.reset();
        this.response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        String callback = RequestUtil.getParam(this.request, "callback", "callback");
        try {
            out = response.getWriter();
            StringBuffer _JSONStr = new StringBuffer();
            _JSONStr.append(callback).append("([");
            for (int i = 0; i < list.size(); ++i) {
                TddData obj = (TddData)list.get(i);
                _JSONStr.append("[\"").append(obj.getDddId()).append("\",");
                _JSONStr.append("\"").append(obj.getName()).append("\"],");
            }
            if (list.size() > 0)
                _JSONStr.deleteCharAt(_JSONStr.lastIndexOf(","));
            _JSONStr.append("])");
            this.jsonString = _JSONStr.toString();
            out.print(this.jsonString);
        }
        catch (Exception e) {
            log.error("加载科室出错", e);
            out.print("[]");
        }
        return null;
    }
    
    /**
     * 查询会员病历
     */
    public String searchMemberCase() {
        String idCard = RequestUtil.getParam(request, "idCard", "-1");
        TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
        if ("-1".equals(idCard)) {
            idCard = userInfo.getId().toString();
        }
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("idCard", idCard);
        try {
            List<TICase> caseList = new ArrayList<TICase>();
            List<Object> list = tiCaseService.findCaseList(paraMap);
            if (list.size() > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                TICase ts = null;
                for (int i = 0; i < list.size(); i++) {
                    Object[] obj = (Object[])list.get(i);
                    ts = new TICase();
                    ts.setId((Integer)obj[0]);
                    String dateStr = format.format((Date)obj[1]);
                    ts.setCreateTimeStr(dateStr);
                    ts.setName(obj[2].toString());
                    caseList.add(ts);
                }
            }
            ActionContext context = ActionContext.getContext();
            context.put("tiList", caseList);
        }
        catch (Exception e) {
            log.error("病例加载失败！", e);
        }
        return "showWebList";
    }
    
    /**
     * 加载科室 json格式
     */
    public String loadDepartMentJson() {
        String code = RequestUtil.getParam(request, "code", "dep");
        List<TddData> list = dataDictionaryService.findAllDataByCode(code);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            JSONArray json = JSONArray.fromObject(list);
            this.jsonString = json.toString();
            this.response.setCharacterEncoding("UTF-8");
            out.print(this.jsonString);
        }
        catch (Exception e) {
            log.error("加载科室出错", e);
            out.print("[]");
        }
        return null;
    }
    
    /**
     * 增加或者修改病例
     */
    public String addCase() {
        try {
            TsSysuser loginUser = null;
            Object obj = this.session.get(Constants.USERINFO_KEY);
            if (obj != null) {
                loginUser = (TsSysuser)obj;
            }
            if (tiCase.getId() == null) {
                tiCase.setCreateTime(new Date());
            }
            else {
                TICase tempCase = tiCaseService.read(tiCase.getId());
                tiCase.setCreateTime(tempCase.getCreateTime());
                tiCase.setImgsrc(tempCase.getImgsrc());
                tiCase.setRealFileName(tempCase.getRealFileName());
            }
            if (null != tiCase) {
                if (null != imgFile && "1".equals(if_has_File)) {
                    String basePath = request.getSession().getServletContext().getRealPath("/");
                    String compressPath = XmlUtil.getValue("imgPath", "sysConfig") + "/";
                    String fileName = "";
                    fileName = new Date().getTime() + imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
                    if (FileUtil.doUpFile(basePath + compressPath + fileName, imgFile)) {
                        tiCase.setImgsrc(compressPath + fileName);
                        tiCase.setRealFileName(imgFileFileName);
                    }
                }
                if ("0".equals(if_has_File)) {
                    tiCase.setImgsrc(null);
                    tiCase.setRealFileName(null);
                }
            }
            tiCase.setAuthorId(loginUser.getId());
            tiCaseService.create(tiCase);
        }
        catch (Exception e) {
            log.error("病例增加失败！", e);
        }
        return "success";
    }
    
    /**
     * 下载文件
     * 
     * @return
     */
    public String downloadFile() {
        Integer rid = RequestUtil.getParam(request, "rid", -1);
        TICase tempCase = tiCaseService.read(rid);
        String basePath = request.getSession().getServletContext().getRealPath("/");// D:\Program
                                                                                    // Files\apache-tomcat-6.0.18\webapps\attendances\
        String compressPath = XmlUtil.getValue("imgPath", "sysConfig") + "/";// fileFloder/
        
        response.setContentType(CONTENT_TYPE);
        // 得到下载文件的名字
        String filename = basePath;
        String filepath = request.getParameter("filepath");
        String oldfilename = request.getParameter("oldfilename");
        
        try {
            //			String basePath = request.getSession().getServletContext().getRealPath("uploadFiles/");
            // 解决中文乱码问题
            //			filename = new String(request.getParameter("filename").getBytes("iso-8859-1"), "gbk");
            // 创建file对象
            File file = new File(filepath + "/" + tempCase.getImgsrc());
            
            // 设置response的编码方式
            response.setContentType("application/x-msdownload");
            
            // 写明要下载的文件的大小
            response.setContentLength((int)file.length());
            
            // 设置附加文件名
            // response.setHeader("Content-Disposition","attachment;filename="+filename);
            
            // 解决中文乱码
            response.setHeader("Content-Disposition", "attachment;filename="
                + new String(tempCase.getRealFileName().getBytes("gbk"), "iso-8859-1"));
            
            // 读出文件到i/o流
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream buff = new BufferedInputStream(fis);
            
            byte[] b = new byte[1024];// 相当于我们的缓存
            
            long k = 0;// 该值用于计算当前实际下载了多少字节
            
            // 从response对象中得到输出流,准备下载
            OutputStream myout = response.getOutputStream();
            
            // 开始循环下载
            while (k < file.length()) {
                int j = buff.read(b, 0, 1024);
                k += j;
                // 将b中的数据写到客户端的内存
                myout.write(b, 0, j);
            }
            // 将写入到客户端的内存的数据,刷新到磁盘
            myout.flush();
        }
        catch (UnsupportedEncodingException e) {
            //			e.printStackTrace();
        }
        catch (FileNotFoundException e) {
            //			e.printStackTrace();
        }
        catch (IOException e) {
            //			e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 加载 web病例信息
     */
    public String loadWebCase() {
        Integer caseId = RequestUtil.getParam(request, "caseId", -1);
        try {
            TICase tempCase = tiCaseService.read(caseId);
            this.request.setAttribute("tiCase", tempCase);
        }
        catch (Exception e) {
            log.error("病例加载失败！", e);
        }
        return "editWebPage";
    }
    
    /**
     * 删除 web病例信息
     */
    public String deleteWebCase() {
        try {
            String deleteIds = request.getParameter("caseId");
            tiCaseService.deleteCase(deleteIds);
        }
        catch (Exception e) {
            log.error("病例删除失败！", e);
        }
        return "success";
    }
    
    public List getDeplist() {
        return deplist;
    }
    
    public void setDeplist(List deplist) {
        this.deplist = deplist;
    }
    
    public TICase getTiCase() {
        return tiCase;
    }
    
    public void setTiCase(TICase tiCase) {
        this.tiCase = tiCase;
    }
    
    public String getJsonString() {
        return jsonString;
    }
    
    public void setJsonString(String jsonString) {
        this.jsonString = jsonString;
    }
    
    public String getIf_has_File() {
        return if_has_File;
    }
    
    public void setIf_has_File(String if_has_File) {
        this.if_has_File = if_has_File;
    }
    
    public File getImgFile() {
        return imgFile;
    }
    
    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }
    
    public String getImgFileFileName() {
        return imgFileFileName;
    }
    
    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }
    
    public String getFlag() {
        return flag;
    }
    
    public void setFlag(String flag) {
        this.flag = flag;
    }
}
